<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片列表 -->
    <el-card>
      <!-- 添加角色按钮 -->
      <el-row>
        <el-col>
          <el-button type="primary">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 角色列表区域 -->
      <el-table :data="rolesList" stripe border>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template v-slot="scope">
            <el-row
              v-for="(item1,i1) in scope.row.children"
              :key="i1"
              :class="['bd-bottom',i1==0?'bd-top':'','v-center']"
            >
              <!-- 一级权限  -->
              <el-col :span="5">
                <el-tag closable @close="removeUserRight(scope.row,item1.id)">{{item1.authName}}</el-tag>
              </el-col>
              <!-- 二级和三级权限 -->
              <el-col :span="19">
                <el-row
                  v-for="(item2,i2) in item1.children"
                  :key="i2"
                  :class="[i2==0?'':'bd-top','v-center']"
                >
                  <!-- 二级权限 -->
                  <el-col :span="6">
                    <el-tag
                      closable
                      @close="removeUserRight(scope.row,item2.id)"
                      type="success"
                    >{{item2.authName }}</el-tag>
                  </el-col>
                  <!-- 三级权限 -->
                  <el-col :span="18">
                    <el-tag
                      closable
                      @close="removeUserRight(scope.row,item3.id)"
                      type="warning"
                      v-for="(item3,i3) in item2.children"
                      :key="item3.id"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template v-slot="scope">
            <el-button size="mini" type="primary" icon="el-icon-edit">编辑</el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete">删除</el-button>
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-setting"
              @click="showRightDialog(scope.row)"
            >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分配权限的对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      width="50%"
      @close="setRightDialogClosed"
    >
      <el-tree
        show-checkbox
        default-expand-all
        :data="rightsList"
        :props="treeDefaultProps"
        node-key="id"
        :default-checked-keys="defKeys"
        ref="rightsTreeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allowRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      rolesList: [],
      setRightDialogVisible: false,
      rightsList: [],
      treeDefaultProps: {
        label: "authName",
        children: "children"
      },
      defKeys: [],
      roleId: ""
    };
  },
  created() {
    this.getRolesList();
  },
  methods: {
    async getRolesList() {
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200)
        return this.$message.error("获取角色列表失败!");
      this.rolesList = res.data;
    },
    // tag标签的close事件
    async removeUserRight(role, id) {
      // 弹框提示
      const confirmRes = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err);
      if (confirmRes !== "confirm") return;
      // 发送删除网络请求
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${id}`
      );
      if (res.meta.status !== 200) return this.$message.error("删除权限失败!");
      //   把服务器响应的最新的权限赋值给当前的角色
      role.children = res.data;
    },
    // 显示分配权限对话框
    async showRightDialog(role) {
      this.roleId = role.id;
      // 获取数据,给列表数组赋值
      const { data: res } = await this.$http.get("rights/tree");
      if (res.meta.status != 200)
        return this.$message.error("获取权限列表失败!");
      this.rightsList = res.data;
      // 递归获取三级权限的id
      this.getLeafKeys(role, this.defKeys);
      // 展示对话框
      this.setRightDialogVisible = true;
    },
    //  利用递归获取权限列表数据
    getLeafKeys(node, arr) {
      if (!node.children) return arr.push(node.id);
      node.children.forEach(item => {
        this.getLeafKeys(item, arr);
      });
    },
    // 分配权限对话框关闭前清空数组
    setRightDialogClosed() {
      this.defKeys = [];
    },
    async allowRights() {
      // 获取选中或者半选中的id
      const arr = [
        this.$refs.rightsTreeRef.getCheckedKeys(),
        this.$refs.rightsTreeRef.getHalfCheckedKeys()
      ];
      const idStr = arr.join(",");
      // 发送网络请求,递交权限分配的id
      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        { rids: idStr }
      );
      if (res.meta.status != 200) return this.$message.error("分配权限失败!");
      this.$message.success("分配权限成功!");
      // 刷新权限列表
      this.getRolesList();
      // 关闭对话框
      this.setRightDialogVisible = false;
    }
  }
};
</script>
<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bd-top {
  border-top: 1px solid #efefef;
}
.bd-bottom {
  border-bottom: 1px solid #efefef;
}
.v-center {
  display: flex;
  align-items: center;
}
</style>
